import 'dart:async';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:flutter/material.dart';

import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/page_home.dart';
import 'package:flutter_note/note/page_login.dart';
import 'package:flutter_note/note/utils.dart';
import 'package:flutter_note/note/base.dart';

class SplashPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SplashPageState();
  }
}

var _count = 6;
String _point = '';

class _SplashPageState extends BaseState<SplashPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      body: Center(
        child: Text(
          '$_point',
          style: TextStyle(fontSize: dim.x50, color: color.green),
        ),
      ),
    );
  }

  final List<Permission> permissions = [
    Permission.Camera,
    Permission.CallPhone,
    Permission.WriteExternalStorage,
    Permission.AlwaysLocation
  ];

  @override
  void initState() {
    super.initState();
    //_countDown();
    requestPermission(0);
  }

  void requestPermission(int position) async {
    bool isPermission =
        await SimplePermissions.checkPermission(permissions[position]);
    if (!isPermission) {
      final res =
          await SimplePermissions.requestPermission(permissions[position]);
      if (res == PermissionStatus.authorized) {
        print(permissions[position].toString() + "已获取权限");
      } else {
        print(permissions[position].toString() + "未获取权限");
      }
    }
    position++;
    if (position < permissions.length) {
      requestPermission(position);
    } else {
      _countDown();
    }
  }

// 倒计时
  Future _countDown() async {
    setState(() {
      _point = _point + ".";
      _count--;
    });
    if (_count >= 1) {
      Future.delayed(Duration(milliseconds: 500), _countDown);
    } else {
      _point = "";
      String token = await SPUtils.getString(Const.SP_TOKEN);
      if (EmptyUtils.isNotEmpty(token)) {
        _login(token);
      } else {
        startToPage(LoginPage());
      }
    }
  }

  //Token登录请求
  _login(String token) async {
    //show();
    Reply reply = await UserManager.getInstance().tokenLogin(token);
    //dismiss();
    if (reply.code == Const.SUCCESS) {
      startToPage(HomePage());
    } else {
      SPUtils.setString(Const.SP_TOKEN, "");
      startToPage(LoginPage());
    }
  }
}
